package com.homedo.odin.solution.controller.mng;

import com.homedo.core.common.base.controller.BaseController;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.base.dto.ResultData;
import com.homedo.core.common.exception.BizException;
import com.homedo.odin.solution.contract.mng.DictDataReq;
import com.homedo.odin.solution.contract.mng.DictDataResp;
import com.homedo.odin.solution.service.bizservice.mng.MngDictDataBizService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import javax.validation.Valid;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by liyi on 2018/5/21.
 */
@Api(description = "字典数据", tags = {"DictData"}, produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/mng")
public class MngDictDataController extends BaseController<MngDictDataBizService> {

    @ApiOperation(value = "mng_修改数据字典", notes = "mng_修改数据字典（首页标题，type为page，key为subhead）", httpMethod = "PUT")
    @PutMapping("/dict_data")
    public ResultData updateDictData(@Valid @RequestBody DictDataReq req,
            BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String defaultMessage = bindingResult.getFieldError().getDefaultMessage();
            return ResultData.newInstance(Meta.CODE_451, defaultMessage);
        }
        if (req == null) {
            throw new BizException(Meta.CODE_451.getCode(), Meta.CODE_451.getMsg());
        }
        if (StringUtils.isEmpty(req.getKey()) || StringUtils.isEmpty(req.getValue())) {
            throw new BizException(Meta.CODE_451.getCode(), Meta.CODE_451.getMsg());
        }
        baseService.updateDictData(req);
        return ResultData.newInstance(Meta.CODE_200, "修改数据字典成功");
    }

    @ApiOperation(value = "mng通过type和key获取value", notes = "mng通过type和key获取value（首页标题，type为page，key为subhead）", response = DictDataResp.class, httpMethod = "GET")
    @GetMapping("/dict_data")
    public ResultData getDictDataByTypeAndKey(
            @ApiParam(value = "字典类型", required = true) @RequestParam("type") String type,
            @ApiParam(value = "字典key", required = true) @RequestParam("key") String key) {
        DictDataResp resp = baseService.getDictDataByTypeAndKey(type, key);
        return ResultData.newInstance(Meta.CODE_200, resp);
    }

}
